﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using BusinessLogic;

namespace Interface.Posts
{
    public partial class PostList : System.Web.UI.Page
    {
        DataConnection dc = new DataConnection();
        protected override void OnInit(EventArgs e)
        {
            gridPost.PageIndexChanging += new GridViewPageEventHandler(gridPost_PageIndexChanging);
        }

        void gridPost_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gridPost.PageIndex = e.NewPageIndex;
            loadPost();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["AdminSession"] != null)
            {
                btnAddPost.Visible = true;
            }  
            loadPost();
        }

        protected void loadPost()
        {
            string sqlStr = "Select * from Post";
            DataTable dt = dc.getData(sqlStr);
            DataTable dtPost = dataTableInitiate();
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    int stt = i + 1;
                    DataRow row = dt.Rows[i];
                    int ID = Convert.ToInt32(row["PostID"].ToString());
                    string imageSource = "~/Images/Post/" + row["ImageSource"].ToString();
                    string title = row["Title"].ToString();
                    string descript = row["ShortDescript"].ToString();
                    
                    DataRow dtRow = dtPost.NewRow();
                    dtRow["ID"] = ID;
                    dtRow["Image"] = imageSource;
                    dtRow["Title"] = title;                    
                    dtRow["Description"] = descript;                    
                    dtPost.Rows.Add(dtRow);
                }
            }
            gridPost.DataSource = dtPost;
            gridPost.DataBind();
        }

        protected DataTable dataTableInitiate()
        {
            DataTable dt = new DataTable();
            DataColumn col = dt.Columns.Add("ID", typeof(int));
            col.AutoIncrement = true;
            col.AutoIncrementStep = 1;
            col.AutoIncrementSeed = 1;
            dt.Columns.Add("Image", typeof(string));
            dt.Columns.Add("Title", typeof(string));            
            dt.Columns.Add("Description", typeof(string));            
            return dt;
        }

        protected void btnAddPost_Click(object sender, EventArgs e)
        {
            Response.Redirect("CreatePost.aspx");
        }
    }
}